import React,{memo,useEffect, useRef, useState,Suspense} from "react";
import type {FC,ReactNode} from 'react'
import "@/assets/style/search.less"
import { getSearchByKeyService } from "@/api/music";
import { addSong } from "@/store/modules/music";
import { UseDispatch } from "react-redux";
import { useAppDispatch } from "@/store";
import { Spin,ConfigProvider} from "antd";
interface IProps{
    children?:ReactNode,
    ifShow:boolean
}
interface song{
    id:number,
    name:string,
    singerName:string,
    songmid:string
}
const SearchBar: FC<IProps>=({ifShow})=>{
    const searchRef = useRef<HTMLDivElement>(null)
    const inputRef=useRef<HTMLInputElement>(null)
    const [searchList,setSearchList]=useState<song[]>([])
    const [isLoading,setIsLoading]=useState<boolean>(false)
    const dispatch=useAppDispatch()
    //记录上一次的搜索关键词
    const preKeyRef=useRef<string>('')

    //处理回车搜索
    const handleSearch = async(e: React.KeyboardEvent<HTMLInputElement>) => {
        if(e.key==='Enter'){

            const input=inputRef.current
            //待节流设计，避免用户在相同关键词下多次按下回车
            if(input&&input.value.trim()!=''&&input.value.trim()!==preKeyRef.current){
              //记录关键词
              preKeyRef.current = input.value.trim();
              //开启加载动画
              setIsLoading(true);
               try {
                 const key = input.value.trim();
                 const res = (await getSearchByKeyService(key)).data;
                 setSearchList(res.map((e, index) => ({ ...e, id: index })));
               } catch (error) {
                 console.error("搜索失败:", error);
                 alert("搜索失败，请重试");
               } finally {
                 setIsLoading(false);
               }
            }
        }
    }

    //处理添加列表
    const handleAdd = (mid:string, event: React.MouseEvent<HTMLSpanElement>) => {
        event.stopPropagation()
        dispatch(addSong(mid))
        alert('添加成功！')
    }

    useEffect(() => {
      const search = searchRef.current;
      if (!search) return;
      if (ifShow) {
        search.style.top = "0";
      } else {
        search.style.top = "-80%";
      }
    }, [ifShow]);
    

    return (
      <div className="search-container" ref={searchRef}>
        <div className="input-bar">
          <input
            type="text"
            placeholder="搜索关键词~"
            ref={inputRef}
            onKeyUp={(event) => handleSearch(event)}
          />
        </div>
        <Spin size="large" spinning={isLoading} tip="正在搜索中....">
          <div className="search-list">
            {searchList.map((e) => (
              <div className="search-item" key={e.id}>
                <div className="left">
                  <div className="name">{e.name}</div>
                  <div className="singer">{e.singerName}</div>
                </div>
                <div
                  className="add bi-plus-lg"
                  onClick={(event) => handleAdd(e.songmid, event)}
                >
                  
                </div>
              </div>
            ))}
            
          </div>
        </Spin>
      </div>
    );
}

export default memo(SearchBar);